var person;
var planWork;
var planComplete;
var perceptionWork;
var perceptionComplete;

var time;
var accessPassFlow; //进站客流
var outPassFlow;   //出站客流

var staTime;
var NBLStatistics;  //诸光路
var STHStatistics;  //虹桥火车站
var XJDStatistics;  //徐泾东

var regionalData; //区域客流密度数据

var categories;
var analysisData;
var iframeUrl;
var isProd = true; //是否为生产环境，生产环境将采用内网IFRAME URL
$("div.system").click(function(){
	document.location.href= "device.html" ;
});
$("div.home").click(function(){
	document.location.href= "index.html" ;
});
$(".gzzx").click(function(){
	document.location.href= "gzzx.html" ;
});
$(function() {
	mytime();
	// 系统时间
	setInterval(function() {
		mytime();
	}, 1000);
	//温湿度
	getMonitorData();
	setInterval(function() {
		getMonitorData();
	}, 30*60*1000);
	 //车站客流趋势
	getPassFlowData(); 
	setInterval(function() {
		getPassFlowData();
	}, 60*60*1000);
	//周边客流统计
	getPeripheralStatisticsData(); 
	setInterval(function() {
		getPeripheralStatisticsData();
	}, 60*60*1000);
	//区域客流密度
	getRegionalPassFlowDensity();   
	setInterval(function() {
		getRegionalPassFlowDensity();
	}, 10*60*1000);
	// 人员信息数据
	getPersonInfoData();
	setInterval(function() {
		getPersonInfoData();
	}, 60*60*1000);
	// 任务信息
	getWorkInfoData();
	setInterval(function() {
		getWorkInfoData();
	}, 60*60*1000);
	//工时分析
	getHourAnalysisData();
	setInterval(function() {
		getHourAnalysisData();
	}, 10*1000);
	
	//文件学习
	geFileStudyData();
	setInterval(function() {
		geFileStudyData();
	}, 24*60*60*1000);
	//引入iframe
	creatIframe();
});

function getMonitorData(){
	sendAjaxRequest('index/monitor', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {
			$("div.temperature").html(jsonObj.data.monitorData.temperature);
			$("div.precipitation").html(jsonObj.data.monitorData.precipitation);
			//$("div.pm2").html(jsonObj.data.monitorData.pm2);
			$("div.ppm p:eq(0)").html(jsonObj.data.monitorData.ppm);
		}else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
		}
	})
}


//工时分析
function getHourAnalysisData(){
	sendAjaxRequest('personnel/hourAnalysis', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.code == "success") {
			if(typeof jsonObj.data =='string' && jsonObj.data.constructor==String)
			{
				var jsonData = eval("(" + jsonObj.data + ")");
				categories = jsonData.categories;
				analysisData = jsonData.analysisData;
			}else{
				categories = jsonObj.data.categories;
				analysisData = jsonObj.data.analysisData;
			}
		    var manHourAnalysisDom = echarts.init(document.getElementById('manHourAnalysis'));
		    manHourAnalysisChart(manHourAnalysisDom)
		} else if (jsonObj.code == "fail") {
			console.log(jsonObj.message);
		}
	})

}
//车站客流趋势
function getPassFlowData() {
	sendAjaxRequest('personnel/flowData', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.code == "success") {
			time = jsonObj.data.time.split(',');
			accessPassFlow = jsonObj.data.accessPassFlow.split(',');
			outPassFlow = jsonObj.data.outPassFlow.split(',');
		} else {
			console.log(jsonObj.message);
		}
	});
    var stationTrendData = {
        legendData: ["进站客流", "出站客流"],
        xData: time,
        seriesFirstData: accessPassFlow,
        seriesLastData: outPassFlow,
    }
    var passengerTrend = echarts.init(document.getElementById('trend'));
    trendChart(passengerTrend,stationTrendData);
	
}

//周边客流统计
function getPeripheralStatisticsData() {
	sendAjaxRequest('personnel/StatisticsData', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.code == "success") {
			staTime = jsonObj.data.time.split(',');
			if(jsonObj.data.NBLStatistics != null)
			{
				NBLStatistics = jsonObj.data.NBLStatistics.split(',');
			}
			if(jsonObj.data.STHStatistics != null)
			{
				STHStatistics = jsonObj.data.STHStatistics.split(',');
			}
			if(jsonObj.data.XJDStatistics != null)
			{
				XJDStatistics = jsonObj.data.XJDStatistics.split(',');
			}
		} else {
			console.log(jsonObj.message);
		}
	});
    var peripheralStatisticsData = {
            legendData: ["诸光路", "徐泾东","虹桥火车站"],
            xData: staTime,
            seriesFirstData: NBLStatistics,
            seriesLastData: XJDStatistics,
            seriesThreeData: STHStatistics,
        }
        var peripheralStatisticsDom = echarts.init(document.getElementById('peripheralStatistics'));
        trendChart(peripheralStatisticsDom,peripheralStatisticsData);
}

//区域客流密度
function getRegionalPassFlowDensity() {
	sendAjaxRequest('personnel/regionalData', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		console.log(jsonObj.data);
		if (jsonObj.code == "success") {
			regionalData = jsonObj.data.dataList;
		} else {
			console.log(jsonObj.message);
		}
	});
    var regionalPassFlowDensityData = {
    		seriesData : regionalData
    }
    var passengerdensity = echarts.init(document.getElementById('density'));
    densityChart(passengerdensity,regionalPassFlowDensityData)
}

//时钟
function mytime() {
	var a = new Date();
	var time = a.toLocaleTimeString();
	var date = a.toLocaleDateString();
	$("span.date").html(date);
	$("span.time").html(time);
}

//生成iframe url
function setIframeUrl(){
	if(isProd){
		//生产环境url
		var origin = window.location.origin;
		origin = origin.replace(window.location.port,"9020"); //SVG与此项目同IP不同端口
		iframeUrl = origin + "/bip/last-location.html";
	}else{
		//测试环境url
		iframeUrl = "http://dev.lziot.cn:8080/bip/last-location.html";
	}
}

//引入iframe
function creatIframe(){
	setIframeUrl();
	$("div.iframe").append(
		"<iframe align=\"left\" width=\"1155px\" height=\"900px\" frameborder=\"no\"  frameborder=\"no\" src="+iframeUrl+"></iframe>"
	)
}

//任务信息
function getWorkInfoData() {
	sendAjaxRequest('index/workInfo', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {
			$("div.fault").html(jsonObj.data.workInfoData.fault);
			$("div.workOrder").html(jsonObj.data.workInfoData.workOrder);
			$("div.processed").html(jsonObj.data.workInfoData.processed);
		} else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
		}
	})
}

//任务信息
function getPersonInfoData() {
	sendAjaxRequest('index/personInfo', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {
			$("div.onDuty").html(jsonObj.data.personInfoData.positionStatus[0]);
			$("div.onGuard").html(jsonObj.data.personInfoData.positionStatus[1]);
			$("div.waitingForPost").html(jsonObj.data.personInfoData.positionStatus[2]);
			person = jsonObj.data.personInfoData.person;
			planWork = jsonObj.data.personInfoData.planWork;
			planComplete = jsonObj.data.personInfoData.planComplete;
			perceptionWork = jsonObj.data.personInfoData.perceptionWork;
			perceptionComplete = jsonObj.data.personInfoData.perceptionComplete;
			var personnelInfo = echarts.init(document.getElementById('personnel'));
			personnelChart(personnelInfo)
		} else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
		}
	})
}

//文件学习
function geFileStudyData(){
	sendAjaxRequest('personnel/fileStudy', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {
			$("div.fileTotal").html(jsonObj.data.fileTotal);
			$("div.studyFile").html(jsonObj.data.studyFile);
		}else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
		}
	})
}

function trendChart(chart,data){
    // chart.clear();
    option = {
	    tooltip: {
	        trigger: 'axis'
	    },
        legend: {
            y: 20,
            data: data.legendData,
            textStyle: {
                fontSize: 14,
                color: '#fff'
            }
        },
        grid: {
            left: 45
        },
        xAxis: [{
            type: "category",
            boundaryGap : true,
            splitLine: {
                show: false
            },
            data: data.xData,
            axisTick: {
                // show: false,
                alignWithLabel: true
            },
            axisLine: {
                lineStyle: {
                    color: '#fff',
                    width: 2
                }
            },
            splitLine: {
                show: false
            },
            axisLabel: {
                // show: false
                textStyle:{
                    color: '#FFFFFF',
                    fontSize:14
                },
                interval: 0
            }
        }],
        yAxis: [{
            type: "value",
            splitNumber: 4,
            axisLine: {
                lineStyle: {
                    color: '#fff',
                    width: 1
                }
            },
            axisLabel: {
                // show: false
                textStyle:{
                    color: '#FFFFFF',
                    fontSize:10
                }
            },
            splitLine: {
                show: true,
                lineStyle: {
                    type: 'dotted'
                }
            },
            axisTick: {
                // show: false,
            },
        }],
        series: [{
            name: data.legendData[0],
            type: "line",
            data: data.seriesFirstData,
            symbol: 'rect',
            // symbolSize: 10,
            clipOverflow: false,
            hoverAnimation: false,
            showSymbol: false,
            itemStyle: {
                normal: {
                    color: '#36B5B0'
                }
            },
            areaStyle: {
                normal: {
                    color: '#36B5B0'
                }
            }
        }, {
            name: data.legendData[1],
            type: "line",
            data: data.seriesLastData,
            symbol: 'rect',
            // symbolSize: 10,
            clipOverflow: false,
            hoverAnimation: false,
            showSymbol: false,
            itemStyle: {
                normal: {
                    color: '#CD6B17'
                }
            },
            areaStyle: {
                normal: {
                    color: '#CD6B17'
                }
            }
        }, {
            name: data.legendData[2],
            type: "line",
            data: data.seriesThreeData,
            symbol: 'rect',
            // symbolSize: 10,
            clipOverflow: false,
            hoverAnimation: false,
            showSymbol: false,
            itemStyle: {
                normal: {
                    color: '#93D704'
                }
            },
            areaStyle: {
                normal: {
                    color: '#93D704'
                }
            }
        }]
    };

    chart.setOption(option);
}

function densityChart(chart,data){
    // chart.clear();
    option = {
        tooltip: {
            trigger: 'axis'
        },
        toolbox: {
            show: false
        },
        xAxis: [{
            type: 'category',
            data: ['上行站台', '下行站台', '3号口闸机', '2号口闸机'],
            axisLine: {
                lineStyle: {
                    color: '#fff'
                }
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#fff',
                fontSize: 14,
                interval: 0
            }
        }],
        yAxis: [{
            type: 'value',
            show: true,
            splitNumber: 5,
            axisTick: {
                show: true
            },
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#fff'
                }
                
            },
            axisLabel: {
                color: '#fff',
                fontSize: 14
            },
            splitLine: {
                show: false
            }
        }],
        axisPointer: {
            show: false
        },
        series: [{
            type: 'bar',
            data: data.seriesData,
            itemStyle: {
                normal: {
                    color: function(params) { 
                        var colorList = ['#42D9B8','#FF7F00','#FE0000','#42D9B8']; 
                        return colorList[params.dataIndex] 
                    }
                }
            },
            label: {
                normal: {
                    show: true,
                    position: 'top',
                    fontSize: 14
                }
            },
            barWidth: 20
        }]
    };
    chart.setOption(option);
}

function personnelChart(chart){
    // chart.clear();
    option = {
        tooltip: {
            trigger: 'axis',
            show:true,
            formatter: function(params) { //设置滑过显示小圆点以及对应数据的位置 方便看数
                var result = params[0].name+'<br>';
                params.forEach(function(item) {
                      result += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + item.color + '"></span>';
                      result +=item.seriesName+": "+'<span style="color:#fff">'+ item.data+"</span><br>"
                });

                    return result;
            },
        },
        legend: {
            data: [
            '计划任务', '感知任务', '已完成'
            ],
            top: 30,
            left: 0,
            itemGap: 5,
            itemWidth: 15,
            itemHeight: 10,
            textStyle:{
               color:'#fff',
               fontSize: 14
            }
        },
        calculable: true,
        grid: {
            y: 70, y2: 30, x2: 60,
            tooltip:{
                show:true
            }
        },
        xAxis: [
            //x轴只显示一个就可以 对应 xAxisIndex: 0,A***数           
            {
                axisLabel :{
                    interval:0,
                    textStyle: {
                        color: '#fff'
                    },
                    show:true
                },
                axisTick: {
                    show: false
                },
                axisLine:{
                    lineStyle:{
                        color:'#fff'
                    },
                    show:false
                },
                data: person,
            },
            //对应 xAxisIndex: 1,B***数 
            {
                type: 'category',
                axisLine: {show: false},
                axisTick: {show: false},
                axisLabel: {show: false},
                splitArea: {show: false},
                splitLine: {show: false},
                data: person
            },
            {
                axisLabel :{
                    interval:0,
                    textStyle: {
                        color: '#fff'
                    },
                    show:false
                },
                axisTick: {
                    show: false
                },
                axisLine:{
                    lineStyle:{
                        color:'#fff'
                    },
                    show:true
                },
                data: person,
            },
            //对应 xAxisIndex: 1,B***数 
            {
                type: 'category',
                axisLine: {show: false},
                axisTick: {show: false},
                axisLabel: {show: false},
                splitArea: {show: false},
                splitLine: {show: false},
                data: person
            }
            
        ],
        yAxis:{
            splitLine: {show: false},//去除网格线
            type: 'value',
            axisLabel: {
                show: true,
                interval:0,
                textStyle: {
                    color: '#fff'
                }
            },
            axisTick: {
                show: false
            },
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#fff'
                }
            }
        },
        axisPointer: {
            show: false
        },
        series: [
        {
            name: '计划任务',
            type: 'bar',
            barGap: '0%',
            barWidth: '30%',
            itemStyle: {
                normal: {
                    color: '#ff7e00', 
                    label: {
                        show: false, 
                        textStyle: {
                            color: '#fff'
                        }
                    }
                }
            },
            label: {
                normal: {
                    show: true,
                    position: 'top',
                    fontSize: 14
                }
            },
            data: planWork
        },
        {
            name: '已完成',
            type: 'bar',
            barGap: '100%',
            barWidth: '20%',
            xAxisIndex: 1,
            itemStyle: {
                normal: {
                    color: '#adadad',
                    label: {
                        show: false, 
                        textStyle: {
                            color: '#27727B'
                        }
                    }
                }
            },
            label: {
                normal: {
                    show: true,
                    position: 'top',
                    fontSize: 14
                }
            },
            data: planComplete
        },
        {
            name: '感知任务',
            type: 'bar',
            barGap: '30%',
            barWidth: '30%',
            itemStyle: {
                normal: {
                    color: '#42d9b9', 
                    label: {
                        show: false, 
                        textStyle: {
                            color: '#fff'
                        }
                    }
                }
            },
            label: {
                normal: {
                    show: true,
                    position: 'top',
                    fontSize: 14
                }
            },
            data: perceptionWork
        },
        {
            name: '已完成',
            type: 'bar',
            barGap: '100%',
            barWidth: '20%',
            xAxisIndex: 1,
            itemStyle: {
                normal: {
                    color: '#adadad',
                    label: {
                        show: false, 
                        textStyle: {
                            color: '#27727B'
                        }
                    }
                }
            },
            label: {
                normal: {
                    show: true,
                    position: 'top',
                    fontSize: 14
                }
            },
            data: perceptionComplete
        }],
    };
    chart.setOption(option);
}

function manHourAnalysisChart (chart){
    // chart.clear();
    var data = [];
    var itemStyle = []
    var dataCount = 10;
    var startTime = +new Date();
    echarts.util.each(categories, function (category, index) {
        var baseTime = startTime;
        for (var i = 0; i < 5; i++) {
            var duration = Math.round(Math.random()*10000000);;
            data.push({
                name: categories[index],
                value: analysisData[index][i],
                itemStyle: {
                    normal: {
                        color: '#FED45E'
                    }
                }
            });
            baseTime += Math.round(Math.random()*1000000);;
        }
    });    

    function renderItem(params, api) {
        var categoryIndex = api.value(0);
        var start = api.coord([api.value(1), categoryIndex]);
        var end = api.coord([api.value(2), categoryIndex]);
        var height = api.size([0, 1])[1] * 0.6;

        var rectShape = echarts.graphic.clipRectByRect({
            x: start[0],
            y: start[1] - height / 2,
            width: end[0] - start[0],
            height: height
        }, {
            x: params.coordSys.x,
            y: params.coordSys.y,
            width: params.coordSys.width,
            height: params.coordSys.height
        });

        return rectShape && {
            type: 'rect',
            shape: rectShape,
            style: api.style()
        };
    }


    option = {
        tooltip: {
            formatter: function (params) {
              return params.name + ':' + timestampToTime(params.value[1]) + '~' + timestampToTime(params.value[2]);
            }
          },
        dataZoom: [{
            type: 'slider',
            filterMode: 'weakFilter',
            showDataShadow: false,
            top: 400,
            height: 10,
            borderColor: 'transparent',
            backgroundColor: '#e2e2e2',
            handleIcon: 'M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z', // jshint ignore:line
            handleSize: 20,
            handleStyle: {
                shadowBlur: 6,
                shadowOffsetX: 1,
                shadowOffsetY: 2,
                shadowColor: '#aaa'
            },
            labelFormatter: ''
        }, {
            type: 'inside',
            filterMode: 'weakFilter'
        }],
        grid: {
            height:200,
            left: 63
        },
        xAxis: {
        	type:'time',
            scale: true,
            axisLine: {
                lineStyle: {
                    color: '#fff'
                }
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#fff',
                fontSize: 12,
                interval: 0
            }
        },
        yAxis: {
            data: categories,
            axisTick: {
                show: false
            },
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#fff'
                }
                
            },
            axisLabel: {
                color: '#fff',
                fontSize: 14
            },
            splitLine: {
                show: false
            }
        },
        series: [{
            type: 'custom',
            renderItem: renderItem,
            itemStyle: {
                normal: {
                    
                }
            },
            encode: {
                x: [1, 2],
                y: 0
            },
            data: data 
        }]
    };
    chart.setOption(option);
}

function timestampToTime(timestamp) {
    var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes() + ':';
    var s = date.getSeconds();
    return h+m+s;
}